package com.itheima.mp.domain.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.dto.UserFormDTO;
import com.itheima.mp.domain.enums.UserStatus;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.service.IUserService;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.mapper.UserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    @Transactional
    public void deductBalance(Long id, Integer money) {

        User user = getById(id);
        if (user == null || user.getStatus() == UserStatus.FROZEN) {
            throw new RuntimeException("用户状态异常！");
        }
        if (user.getBalance() < money) {
            throw new RuntimeException("用户余额不足！");
        }
//        baseMapper.deductBalance(id, money);
        // 扣减余额，如果扣减后为0就冻结
        int remainBalance = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance, remainBalance)
                .set(remainBalance == 0, User::getStatus, 2)
                .eq(User::getId, id)
                .eq(User::getBalance, user.getBalance()) // 乐观锁，防止并发更新，比较where条件里的值是否被修改，即where条件里加上对balance的判断，必须是等于查到的balance，证明没有人修改过
                .update();
    }

    @Override
    public List<User> queryUsers(String name, Integer status, Integer minBalance, Integer maxBalance) {
        return lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .ge(minBalance != null, User::getBalance, minBalance)
                .le(maxBalance != null, User::getBalance, maxBalance)
                .list();
    }

    @Override
    public UserVO queryUserAndAddressById(Long id) {
        // 1. 查询用户
        User user = getById(id);
        if (user == null || user.getStatus() == UserStatus.FROZEN) {
            throw new RuntimeException("用户状态异常！");
        }
        // 2. 查询地址
        List<Address> addresses = Db.lambdaQuery(Address.class).eq(Address::getUserId, id).list();
        // 3. 组装VO
        // 3.1 组装用户VO
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        // 3.2 组装地址VO
        if (CollUtil.isNotEmpty(addresses)) {
            userVO.setAddresses(BeanUtil.copyToList(addresses, AddressVO.class));
        }
        return userVO;
    }

    @Override
    public List<UserVO> queryUserAndAddressByIds(List<Long> ids) {
        // 1. 查询用户
        List<User> users = listByIds(ids);
        if (CollUtil.isEmpty(users)) {
            return Collections.emptyList();
        }
        // 2. 查询地址
        // 2.1 获取用户id集合
        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());
        // 2.2 根据用户id查询出每个用户的全部地址
        List<Address> addresses = Db.lambdaQuery(Address.class).in(Address::getUserId, userIds).list();
        // 2.3 转换地址VO
        List<AddressVO> addressVOList = BeanUtil.copyToList(addresses, AddressVO.class);
        // 2.4 用户地址集合分组处理
        Map<Long, List<AddressVO>> addressMapUserId = new HashMap<>();
        if (CollUtil.isNotEmpty(addressVOList)) {
            addressMapUserId = addressVOList.stream().collect(Collectors.groupingBy(AddressVO::getUserId));
        }
        // 3. 转换VO返回
        ArrayList<UserVO> list = new ArrayList<>();
        for (User user : users) {
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            userVO.setAddresses(addressMapUserId.get(user.getId()));
            list.add(userVO);
        }
        return list;
    }

    // 原始写法
//    @Override
//    public PageDTO<UserVO> queryUsersPage(UserQuery userQuery) {
//        String name = userQuery.getName();
//        Integer status = userQuery.getStatus();
//        // 1. 构建分页条件
//        Page<User> userPage = Page.of(userQuery.getPageNo(), userQuery.getPageSize());
//        if (StrUtil.isNotBlank(userQuery.getSortBy())) {
//            userPage.addOrder(new OrderItem(userQuery.getSortBy(), userQuery.getIsAsc()));
//        } else {
//            userPage.addOrder(new OrderItem("update_time", false)); // false 表示降序；true 表示升序
//        }
//        // 2. 分页查询
//        Page<User> pageResult = lambdaQuery().like(name != null, User::getUsername, name)
//                .eq(status != null, User::getStatus, status)
//                .page(userPage);
//        // 3. 封装VO，最终返回类型为 PageDTO<UserVO>
//        PageDTO<UserVO> resultPageDTO = new PageDTO<>();
//        // 总条数
//        resultPageDTO.setTotal(pageResult.getTotal());
//        // 总页数
//        resultPageDTO.setPages(pageResult.getPages());
//        // 当前页数据
//        List<User> records = pageResult.getRecords();
//        if (CollUtil.isEmpty(records)) {
//            resultPageDTO.setList(Collections.emptyList());
//            return resultPageDTO;
//        }
//        // 转换VO
//        resultPageDTO.setList(BeanUtil.copyToList(records, UserVO.class));
//        return resultPageDTO;
//    }
    // 使用封装的公共方法改进
    @Override
    public PageDTO<UserVO> queryUsersPage(UserQuery userQuery) {
        String name = userQuery.getName();
        Integer status = userQuery.getStatus();
        // 1. 构建分页条件
        Page<User> page = userQuery.toMpPageDefaultSortByCreateTimeDesc();

        // 2. 分页查询
        Page<User> p = lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .page(page);

        // 3. 封装VO结果
        return PageDTO.of(p, user -> {
            // 拷贝基础属性
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            // 处理特殊逻辑
            userVO.setUsername(userVO.getUsername().substring(0, userVO.getUsername().length() - 2) + "**");
            return userVO;
        });
    }
}
